package com.ymx.darling.expression;

import com.ymx.darling.exception.ExpressionException;

/**
 * 运算的静态类
 * @author 爱Java的小于
 */
public class Calculate {
    private static boolean computeNumber(Object one, Object two, String code) {
        if (!(one instanceof Number) || !(two instanceof Number)) {
            throw new ExpressionException("操作数:"+one+"和操作数:"+two+"不是数值型不能参数比较运算");
        }
        double d1 = ((Number) one).doubleValue();
        double d2 = ((Number) two).doubleValue();
        switch (code) {
            case ">":
                return d1 > d2;
            case ">=":
                return d1 >= d2;
            case "<":
                return d1 < d2;
            case "<=":
                return d1 <= d2;
            case "==":
                return d1 == d2;
            default:
                return d1 != d2;
        }
    }

    public static boolean greaterThan(Object one, Object two) {
        return computeNumber(one, two, ">");
    }

    public static boolean lessThan(Object one, Object two) {
        return computeNumber(one, two, "<");
    }

    public static boolean equalTo(Object one, Object two) {
        // 如果两个对象都为 null，直接返回 true
        if (one == null && two == null) {
            return true;
        }
        // 如果一个为 null，另一个不为 null，直接返回 false
        if (one == null || two == null) {
            return false;
        }
        // 如果两个对象都是 Number 类型，使用专门的数字比较逻辑
        if (one instanceof Number && two instanceof Number) {
            return computeNumber(one, two, "==");
        }
        // 如果两个对象的类型不同，直接返回 false
        if (!one.getClass().equals(two.getClass())) {
            return false;
        }
        // 对于非数字类型，直接比较其字符串表示形式
        return String.valueOf(one).equals(String.valueOf(two));
    }

    public static boolean greaterThanOrEqualTo(Object one, Object two) {
        return computeNumber(one, two, ">=");
    }

    public static boolean lessThanOrEqualTo(Object one, Object two) {
        return computeNumber(one, two, "<=");
    }

    public static boolean notEqualTo(Object one, Object two) {
        return !equalTo(one, two);
    }

    public static boolean andTo(Object one, Object two) {
        return computeBoolean(one, two, "and");
    }

    public static boolean orTo(Object one, Object two) {
        return computeBoolean(one, two, "or");
    }

    private static boolean computeBoolean(Object one, Object two, String code) {
        if (one instanceof Boolean && two instanceof Boolean) {
            boolean bool1 = (Boolean) one;
            boolean bool2 = (Boolean) two;
            if (code.equals("and")) {
                return bool1 && bool2;
            } else {
                return bool1 || bool2;
            }
        } else {
            throw new ExpressionException(String.format("操作数%s与%s不能使用逻辑运算符%s运算", one, two, code));
        }
    }
}
